package com.attendance.controller;

import com.attendance.Utils.Converter.RecordConverter;
import com.attendance.Utils.PaginationUtil;
import com.attendance.model.Biz.BizRecord;
import com.attendance.model.Form.RecordForm;
import com.attendance.model.Record;
import com.attendance.model.Result.Response;
import com.attendance.model.Result.ResultCode;
import com.attendance.service.IRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Inuyasha on 2016/12/1.
 */
@RestController
@RequestMapping("/record")
public class RecordController {

    @Autowired
    private IRecordService recordService;

    @RequestMapping(value = "",method = RequestMethod.GET)
    public Response getAll(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows,
                           @RequestParam(defaultValue = "id") String sort, @RequestParam(defaultValue = "asc") String order,
                           @ModelAttribute RecordForm recordForm){
        PaginationUtil.preset(page, rows, sort, order);
        Response response = new Response();
        List<BizRecord> list = recordService.getAll(recordForm);
        response.putResult(list);
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    public Response add(@ModelAttribute RecordForm recordForm){
        Response response = new Response();
        try {
            Record record = RecordConverter.convert(recordForm);
            recordService.insertSelective(record);
        } catch (Exception e) {
            return new Response(ResultCode.RECORD_ADD_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.DELETE)
    public Response delete(@ModelAttribute RecordForm recordForm){
        Response response = new Response();
        try {
            Record record = RecordConverter.convert(recordForm);
            recordService.deleteById(record.getId());
        } catch (Exception e) {
            return new Response(ResultCode.RECORD_DELETE_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.PUT)
    public Response update(@ModelAttribute RecordForm recordForm){
        Response response = new Response();
        try {
            Record record = RecordConverter.convert(recordForm);
            recordService.updateSelectiveById(record);
        } catch (Exception e) {
            return new Response(ResultCode.RECORD_UPDATE_ERROR);
        }
        return response;
    }
}
